<?php
namespace app\admin\controller;

use app\common\model\Vip as VipModel;
use app\common\controller\AdminBase;

/**
 * 费用管理
 * Class Article
 * @package app\admin\controller
 */
class Vip extends AdminBase
{
    protected $vip_model;

    protected function initialize()
    {
        parent::initialize();
        $this->vip_model = new VipModel();
    }

    /**
     * 內容管理
     * @param string $keyword 关键词
     * @param int    $page
     * @return mixed
     */
    public function index( $keyword = '', $page = 1)
    {
        $map   = [];

        if (!empty($keyword)) {
            $map['title'] = ['like', "%{$keyword}%"];
        }
        $vip_list  = $this->vip_model->where($map)->order(['create_time' => 'DESC'])->paginate(15, false, ['page' => $page]);

        return $this->fetch('index', ['vip_list' => $vip_list, 'keyword' => $keyword]);
    }

    /**
     * 添加內容
     * @return mixed
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 保存內容
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $validate_result = $this->validate($data, 'Vip');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if ($this->vip_model->allowField(true)->save($data)) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑內容
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $vip = $this->vip_model->find($id);
        return $this->fetch('edit', ['vip' => $vip]);
    }

    /**
     * 更新內容
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $validate_result = $this->validate($data, 'Vip');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {

                if ($this->vip_model->allowField(true)->save($data, $id) !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除內容
     * @param int   $id
     * @param array $ids
     */
    public function delete($id = 0, $ids = [])
    {
        $id = $ids ? $ids : $id;
        if ($id) {
            if ($this->vip_model->destroy($id)) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('请选择需要删除的內容');
        }
    }

}